<script setup>
import * as echarts from "echarts";
import {onMounted, ref} from "vue";
import {queryUserNums} from "@/api/user.js";
import {queryOnlineUserCount} from "@/api/statistics.js";

const totalUsers = ref(0)
const onlineUsers = ref(0)
let myChart = null

const getOnlineUser = () => {
  queryOnlineUserCount()
    .then(res => {
      onlineUsers.value = res.data.data
      updateChart()
    })
    .catch(error => {
      console.log(error)
    })
}

const getUserNums = () => {
  queryUserNums()
    .then(res => {
      totalUsers.value = res.data.data
      updateChart()
    })
    .catch(error => {
      console.log(error)
    })
}

const updateChart = () => {
  if (!myChart || totalUsers.value === 0) return

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: true,
          position: 'center',
          formatter: `${Math.round((onlineUsers.value / totalUsers.value) * 100)}%\n在线率`,
          fontSize: '14',
          color: '#333'
        },
        emphasis: {
          disabled: true
        },
        labelLine: {
          show: false
        },
        data: [
          {
            value: onlineUsers.value,
            name: '在线用户',
            itemStyle: {
              color: '#1f77ff'
            }
          },
          {
            value: totalUsers.value - onlineUsers.value,
            name: '离线用户',
            itemStyle: {
              color: '#E1E1E1'
            }
          }
        ]
      }
    ]
  };

  myChart.setOption(option)
}

const initChart = () => {
  const chartDom = document.getElementById('onlineUser')
  myChart = echarts.init(chartDom)

  // 监听窗口大小变化，重绘图表
  window.addEventListener('resize', () => {
    myChart && myChart.resize()
  })
}

onMounted(() => {
  initChart()
  getUserNums() // 获取总用户数
  getOnlineUser() // 立即获取一次数据
})
</script>

<template>
  <div class="container">
    <div class="left">
      <div class="card-title">在线用户数</div>
      <div class="card-content">{{ onlineUsers }}</div>
    </div>
    <div class="right">
      <div class="online-user-statistics-container">
        <div id="onlineUser"></div>
      </div>
    </div>
  </div>
</template>

<style scoped>
#onlineUser {
  width: 100px;
  height: 100px;
}

.card-title {
  font-size: 18px;
}

.container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-content {
  height: 70px;
  margin-top: 10px;
  font-size: 20px;
  font-weight: bold;
}
</style>
